# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter

# 使用管道要在settings 中配置
class ScrapyDushuwangPipeline:

    def open_spider(self, spider):
        self.fp = open('dushuwang.json', 'w', encoding='utf-8')
        print('+++++++++++++++++++++++++++++++')

    def process_item(self, item, spider):
        self.fp.write(str(item))
        return item

    def close_spider(self, spider):
        self.fp.close()
        print('-------------------------------')


# 加载settings 文件
from scrapy.utils.project import get_project_settings
import pymysql

# 自定义 mysql 管道
# 注意：自定义的管道要在 settings 中配置
class MysqlPipeline:
    def open_spider(self, spider):
        settings = get_project_settings()
        # 配置mysql参数
        # DB_HOST = 'localhost'
        # DB_PORT = 3306
        # DB_USER = 'root'
        # DB_PASSWORD = 'mysql'
        # DB_NAME = 'db1'
        # DB_CHARSET = 'utf8'
        self.host = settings['DB_HOST']
        self.port = settings['DB_PORT']
        self.user = settings['DB_USER']
        self.password = settings['DB_PASSWORD']
        self.name = settings['DB_NAME']
        self.charset = settings['DB_CHARSET']

        # 打开连接
        self.connect()

    def connect(self):
        self.conn = pymysql.connect(
                                    user=self.user,
                                    password=self.password,
                                    host=self.host,
                                    db=self.name,
                                    port=self.port,
                                    charset=self.charset,
        )

        self.cursor = self.conn.cursor()

    def process_item(self, item, spider):
        sql = 'insert into book(name, path) values ("{}","{}")'.format(item['name'], item['src'])
        # 执行sql 并提交
        self.cursor.execute(sql)
        self.conn.commit()

        return item

    def close_spider(self, spider):
        # 关闭
        self.cursor.close()
        self.conn.close()
